package com.bw.paper.mvp.view.Activity;

import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bw.paper.App;
import com.bw.paper.R;
import com.bw.paper.db.UserEntityDao;
import com.bw.paper.entity.BroadcastEntity;
import com.bw.paper.entity.UploadEntity;
import com.bw.paper.entity.UserEntity;
import com.bw.paper.mvp.base.model.BaseEntity;
import com.bw.paper.mvp.base.view.BaseActivity;
import com.bw.paper.mvp.contact.LoginContract;
import com.bw.paper.mvp.di.DaggerLoginComponent;
import com.bw.paper.mvp.di.LoginModules;
import com.bw.paper.mvp.model.LoginModel;
import com.bw.paper.mvp.presenter.LoginPresenter;
import com.bw.paper.utils.LogUtils;
import com.bw.paper.utils.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.annotations.Nullable;

public class UpUserActivity extends BaseActivity<LoginPresenter> implements LoginContract.LoginView, View.OnClickListener {
    private RelativeLayout updateRl;
    private ImageView backUp;
    private RelativeLayout txRl;
    private ImageView usernameTx;
    private RelativeLayout nameRl;
    private TextView usernameMsd;
    private RelativeLayout sexRl;
    private TextView usernameSex;
    private  UserBroadcast broadcast;
    private Button secrecy;
    private Button man;
    private Button girl;
    private Button cancel;
    private Button photograph;
    private Button photoalbum;
    private Button photocancel;
    private   LoginPresenter loginPresenter;

    @Override
    public View addStatusView() {
        return f(R.id.update_rl);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcast);
        Log.e("asd","UpdateUserActivity:onDestroy");

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id==R.id.sex_rl){

            LinearLayout pop_sax = (LinearLayout) getLayoutInflater().inflate(R.layout.pop_sax, null);
            secrecy = (Button) pop_sax.findViewById(R.id.secrecy);
            man = (Button) pop_sax.findViewById(R.id.man);
            girl = (Button) pop_sax.findViewById(R.id.girl);
            cancel = (Button) pop_sax.findViewById(R.id.cancel);
            PopupWindow  popupWindow = new PopupWindow();
            popupWindow.setContentView(pop_sax);
            popupWindow.setFocusable(true);
            secrecy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = null;
                    try {
                         unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
                        if (unique != null) {
                            unique.setUser_sex("0");
                        }
                        App.getInstance().getDaoSession().update(unique);
                        LogUtils.show(""+App.getInstance().getDaoSession().loadAll(UserEntity.class));
                        usernameSex.setText("保密");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    popupWindow.dismiss();
                }
            });
            man.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = null;
                    try {
                         unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

                        if (unique != null) {
                            unique.setUser_sex("1");
                            unique.setUser_integral(1);
                        }
                        App.getInstance().getDaoSession().update(unique);
                        LogUtils.show(""+App.getInstance().getDaoSession().loadAll(UserEntity.class));
                        usernameSex.setText("男");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    popupWindow.dismiss();

                }
            });
            girl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = null;
                    try {
                         unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

                        if (unique != null) {
                            unique.setUser_sex("0");
                        }
                        App.getInstance().getDaoSession().update(unique);
                        LogUtils.show(""+App.getInstance().getDaoSession().loadAll(UserEntity.class));
                        usernameSex.setText("女");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    popupWindow.dismiss();
                }
            });
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();

                }
            });
            popupWindow.setOutsideTouchable(true);
            popupWindow.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setAnimationStyle(R.style.Popupwindow);
            int[] location = new int[2];
            v.getLocationOnScreen(location);

//透明
            WindowManager.LayoutParams attributes = getWindow().getAttributes();
            attributes.alpha = 0.5f;
            getWindow().setAttributes(attributes);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 1f;
                    getWindow().setAttributes(attributes);
                }
            });

            popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, -location[1]);
        }

        if (id==R.id.tx_rl){
            LinearLayout pop_img = (LinearLayout) getLayoutInflater().inflate(R.layout.pop_img, null);
            photograph = (Button)pop_img. findViewById(R.id.photograph);
            photoalbum = (Button)pop_img. findViewById(R.id.photoalbum);
            photocancel = (Button)pop_img. findViewById(R.id.photocancel);
            PopupWindow popupWindow = new PopupWindow();
            popupWindow.setContentView(pop_img);
            popupWindow.setOutsideTouchable(true);

            photograph.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//                    path = "/sdcard/DCIM/Camera/" + System.currentTimeMillis() + ".jpg";
                    path = "/sdcard/DCIM/Camera/"+getUri();
                    Uri uriForFile = FileProvider.getUriForFile(UpUserActivity.this,
                            "com.bw.paper",
                            new File(path));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
                    startActivityForResult(intent, 111);
                    popupWindow.dismiss();
                }
            });
            photoalbum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 555);
                    popupWindow.dismiss();


                }
            });
            photocancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();

                }
            });
            //设置宽高
            popupWindow.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setAnimationStyle(R.style.Popupwindow);
            int[] location = new int[2];
            v.getLocationOnScreen(location);

            WindowManager.LayoutParams attributes = getWindow().getAttributes();
            attributes.alpha = 1.5f;
            getWindow().setAttributes(attributes);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 1f;
                    getWindow().setAttributes(attributes);
                }
            });
            popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, -location[1]);
        }

        if (id==R.id.back_up){

            try {
                UserEntity unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

                com.blankj.utilcode.util.LogUtils.json(unique);
                if(unique!=null){
                    loginPresenter.requestUpDataUser(unique);
                }else {
                    ToastUtils.showMsg("aaa");
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
            finish();
//            startPage(FragmActivity.class);
        }
        if (id==R.id.name_rl){
            startPage(UpdataNameActivity.class);

        }
    }

    public class UserBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadcastEntity.UPDATENAME)){
                String username = intent.getStringExtra("username");
                //赋值页面一
                usernameMsd.setText(username);
//11
                try {
                    UserEntity unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
                    if (unique != null) {
                        unique.setUser_name(username);
                    }
                    App.getInstance().getDaoSession().update(unique);
                    LogUtils. show(""+App.getInstance().getDaoSession().loadAll(UserEntity.class));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public int bindlayout() {
        return R.layout.activity_updata;
    }

    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.VIBRATE,
                    Manifest.permission.WAKE_LOCK
            },100);}

        updateRl = (RelativeLayout) findViewById(R.id.update_rl);
        backUp = (ImageView) findViewById(R.id.back_up);
        txRl = (RelativeLayout) findViewById(R.id.tx_rl);
        usernameTx = (ImageView) findViewById(R.id.username_tx);
        nameRl = (RelativeLayout) findViewById(R.id.name_rl);
        usernameMsd = (TextView) findViewById(R.id.username_msd);
        sexRl = (RelativeLayout) findViewById(R.id.sex_rl);
        usernameSex = (TextView) findViewById(R.id.username_sex);

        sexRl.setOnClickListener(this::onClick);
        txRl.setOnClickListener(this::onClick);

        backUp.setOnClickListener(this::onClick);
        nameRl.setOnClickListener(this::onClick);
//        广播发送文字
        broadcast = new UserBroadcast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastEntity.UPDATENAME);
        registerReceiver(broadcast,filter);

        try {
            UserEntity unique1 = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

            String user_img = unique1.getUser_img();
            Glide.with(this).load(user_img).circleCrop().into(usernameTx);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            UserEntity unique2 = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

            if (unique2.getUser_sex().equals("1")) {
                usernameSex.setText("男");
            } else if (unique2.getUser_sex().equals("0")) {
                usernameSex.setText("女");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
//            登录传

        UserEntity unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

        String user_name = unique.getUser_name();
        usernameMsd.setText(user_name);

    }

    @Override
    public void inject() {
        DaggerLoginComponent.builder().loginModules(new LoginModules(this))
                .build().injectUpUser(this);

    }

    @Override
    public void initData() {
         loginPresenter = new LoginPresenter(new LoginModel(), this);
//         usernameMsd.setText(user_name);
        UserEntity unique = null;
        try {
             unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (unique!=null){
            String user_name = unique.getUser_name();
            usernameMsd.setText(user_name);
        }


    }

    @Override
    public void refreshView(BaseEntity entity) {
        if (entity instanceof UploadEntity){
            UploadEntity baseEntity1 = (UploadEntity) entity;
            if (baseEntity1.getStatuesCode().equals("200")){
                Log.e("====","上传头像服务器成功");
                Toast.makeText(this, ""+baseEntity1.getMsg(), Toast.LENGTH_SHORT).show();
            }else {
                Log.e("=====","上传头像服务器成功"+baseEntity1.getMsg());
            }
        }else {
            if (entity.status.equals("200")){
                Log.e("======","数据"+entity.message);
            }else {
                Log.e("======",""+entity.message);
            }
        }

    }
    private String path;
    private String uri;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111 && resultCode == Activity.RESULT_OK) {
            Log.e("===============",""+path);
            Glide.with(this).load(path).transform(new CircleCrop()).into(usernameTx);
            getUpload(path);

            try {
                UserEntity unique =App.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                        .where(UserEntityDao.Properties.Id.eq(1))
                        .unique();
                if (unique != null) {
                    unique.setUser_img(path);
                }
                App.getInstance().getDaoSession().update(unique);
                LogUtils.show(""+App.getInstance().getDaoSession().loadAll(UserEntity.class));

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 555 && resultCode == Activity.RESULT_OK) {
            Uri data1 = data.getData();
            Cursor cursor = getContentResolver().query(data1, null, null, null, null);
            if (cursor!=null){
                if (cursor.moveToFirst()){
                    uri=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
            }
            Glide.with(this).load(data1).transform(new CircleCrop()).into(usernameTx);

            try {
                UserEntity unique = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);

                if (unique != null) {
                    unique.setUser_img( uri);
                    unique.setUser_integral(1);
                }
                App.getInstance().getDaoSession().update(unique);
                LogUtils.show(""+App.getInstance().getDaoSession().loadAll(UserEntity.class));

            } catch (Exception e) {
                e.printStackTrace();
            }

            Log.e("===============",""+uri);
            getUpload(uri+"");

        }
    }



    //照片存储名称
    public String getUri(){
        Date date = new Date();
        SimpleDateFormat yyyyMMdd_hHmmss = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String u=yyyyMMdd_hHmmss.format(date);
        return "IMG_"+u+".jpg";
    }
    //上传图片
    public void getUpload(String uri){
        loginPresenter.RequestUpload(uri);

    }
}
